package lucene_ik;

import java.io.File;
import java.io.IOException;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.IndexWriterConfig.OpenMode;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import org.wltea.analyzer.lucene.IKAnalyzer;

public class Index {

	/**
	 * @param args
	 */
	// Lucnen 索引存放路径
	static String indexPath = "ikindex";
	// Lucene Document的域名
	static String fileName_id="ID";
	static String fieldName_title="title";
	static String fieldName_content="content";

	public Index(Item item) {
		

		// 检索内容
		String id=item.getId().toString();
		String title =item.getTitle();
		String content =item.getContent();
		
		// 实例化IKAnalyzer分词器
		Analyzer analyzer = new IKAnalyzer(true);
		Directory dir = null;
		IndexWriter iwriter = null;

		// 建立索引对象

		try {
			dir = FSDirectory.open(new File(indexPath));

			// 配置IndexWriterConfig
			IndexWriterConfig iwConfig = new IndexWriterConfig(
					Version.LUCENE_45, analyzer);
			iwConfig.setOpenMode(OpenMode.CREATE_OR_APPEND);
			iwriter = new IndexWriter(dir, iwConfig);
			// 写入索引
			Document doc = new Document();
			Field f1 = new Field(fileName_id, id, TextField.TYPE_STORED);
			Field f2 = new Field(fieldName_title, title, TextField.TYPE_STORED);
			Field f3 = new Field(fieldName_content, content, TextField.TYPE_STORED);
			doc.add(f1);
			doc.add(f2);
			doc.add(f3);
			iwriter.addDocument(doc);
			iwriter.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
//		Item list1 = new Item(1, "浙江传媒学院新闻", "浙江传媒学院是一所高校");
//		Index index=new Index(list1);
//		System.out.print("success");

	}

}
